<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/10/27
 * Time: 15:15
 */
namespace AuctionBack\Controller;

use AuctionCore\CarResource\CarModel;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\CarOwner\Owner;
use AuctionCore\CarResource\CarReport;
use AuctionCore\Common\Page;
use AuctionCore\Account\Back\Employee;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\Dispute\Dispute;
use AuctionCore\Cashier\Payment as CashierPayment;
use AuctionBack\Logic\TransferLogic;


/**
 * Class PurchaseOrderController
 * @package AuctionBack\Controller
 */
class PurchaseOrderController extends BaseController
{

    /**
     * 员工编号
     *
     * @var int
     */
    protected $emp_id = 0;

    /**
     * 采购单构造方法
     *
     * PurchaseOrderController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    /**
     * 查询采购单列表
     */
    public function purchase_order_list()
    {
        $p = I('request.p/d', 1);
        $p = $p < 2 ? 1 : $p;
        $limit = 10;
        $params = [];
        $params['purchase_order_nu'] = I('request.purchase_order_nu');
        $params['order_no'] = I('request.order_no');
        $params['starttime'] = I('request.starttime');
        $params['endtime'] = I('request.endtime');

        $location_area = I('get.location_area', 0);
        if (!$location_area) {
            $location_area = $this->user_info['bc_code'];
        } else {
            $location_area = [$location_area];
        }
        $params['location_area'] = $location_area;

        //print_r($this->user_info['bc_code']);die();
        $obj = new PurchaseOrder();
        $data = $obj->getList($p, $limit, $params);

        unset($params['location_area']);
        $page = new Page($data['total'], $limit, $params);
        $page_data = $page->page_data();
        $arr = [
            'list' => $data['list'],
        ];
        $this->assign('params', $params);
        $this->assign('page_data', $page_data);
        $this->assign('p', $p);
        $this->assign('arr', $arr);
        $this->display('list');
    }

    /**
     * 获取采购单详情
     *
     * @return array
     */
    public function detail()
    {
        $arr = $this->getDetailData();

        $arr['order_info']['is_dispute'] = true;
        $sid = $arr['purchase_order']['sid'];//order_status
        $orderInfo = AuOrder::getNewestOrderBySid($sid);
        $arr['order_info'] = $orderInfo;
        //$list['order_info']['order_status'] = $orderInfo['status'];

        $purchaseOrderId = $arr['purchase_order']['id'];
        $arr['order_info']['is_dispute'] = true;
        $condition['order_id'] = $orderInfo['order_id']; //拍单号
        $condition['od_type'] = 2; //客户类型 2 车主
        $condition['order_status'] = $orderInfo['status'];//拍单状态
        $disputeCount = Dispute::getDisputeByPurchaseOrder($condition);
        if ($disputeCount > 0) {
            $arr['order_info']['is_dispute'] = false; //不能发起争议
        }
        //检查权限
        $rules = "CaiGouDanSuoDing";
        $e = new Employee($this->user_info['username']);
        $lock = $e->check_auth($rules);
        $params['lock'] = $lock;

        $rules = "CaiGouDanJieSuo";
        $e = new Employee($this->user_info['username']);
        $unLock = $e->check_auth($rules);
        $params['un_lock'] = $unLock;

        $this->assign('params', $params);
        $this->assign('arr', $arr);
        $this->display();
    }


    /**
     * 得到
     *
     * @return array
     */
    public function getDetailData()
    {
        $id = I('request.id');
        $obj = new PurchaseOrder($id);
        $purchaseOrderInfo = $obj->viewById();
        if (empty($purchaseOrderInfo)) { //如果传来无效的采购单号
            $this->display();
        }

        $orderId = $purchaseOrderInfo['order_id']; //拍单号

        $orderObj = new AuOrder($orderId);
        $orderInfo = $orderObj->detail();

        $carId = $purchaseOrderInfo['car_id']; //车辆编号
        $carObj = new Car($carId);

        $carInfo = $carObj->detail();
        $ownerId = $carInfo['owner_id'];
        $carInfo = $this->sortingCarData($carInfo);

        $carInfo['pointer_mileage'] = formatMileage($carInfo['pointer_mileage']);
        //print_r($carInfo);

        $carOwner = new Owner($ownerId);
        $carOwnerInfo = $carOwner->detail();
        $carOwnerInfo['owner_type_name'] = C('OWNER_TYPE_NAME')[$carOwnerInfo['owner_type']];

        $transferLogic = new TransferLogic();
        $transferInfo = $transferLogic->getTransferLogInfoByOrderId($orderInfo['order_id']);

        $arr = [
            'purchase_order' => $purchaseOrderInfo,
            'car_info' => $carInfo,
            'car_owner' => $carOwnerInfo,
            'order_info' => $orderInfo,
            'transfer_info' => $transferInfo,
        ];
        return $arr;
    }

    /**
     * 整合车的数据
     *
     * @param $carInfo 车源信息
     * @return mixed
     */
    public function sortingCarData($carInfo)
    {
        $show_from = $this->get_from();  //获取渠道来源信息
        $carId = $carInfo['car_id'];
        $comefrom = M("car_owner a")
            ->join('INNER JOIN ' . C('DB_PREFIX') . 'cars AS b ON a.owner_id=b.owner_id')
            ->field('comefrom')
            ->where('b.car_id=' . $carId)
            ->find();

        $compositeState = $carInfo['composite_state'];
        $accLevel = $carInfo['accident_level'];
        $carInfo['car_level'] = $compositeState . $accLevel; //车况等级

        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($carInfo['brand_id'], 'brand');
        $series = $cm->get_model_by_id($carInfo['series_id'], 'series');
        $model = $cm->get_model_by_id($carInfo['model_id']);

        // 品牌，车型
        $carInfo['model_show'] = $brand['name'] . " " . $series['name'] . ' ' . $model['name'] . ' ' . $carInfo['car_cc'] . ($carInfo['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $carInfo['gearbox']);
        $city = new \AuctionCore\Other\Address();
        $reg_city = $city->get_name_by_code($carInfo['reg_city']);
        $reg_area = $city->get_name_by_code($carInfo['reg_area']);
        $carInfo['location_area_str'] = $city->get_name_by_code($carInfo['location_area']);
        $carInfo['reg_city'] = $reg_city . " " . $reg_area; //注册地 = 注册城市 + 区域
        $carInfo['emission'] = C('EMISSION.' . $carInfo['emission']); //排放标准
        $carInfo['car_type'] = C('CAR_TYPE.' . $carInfo['car_type']);//车型
        $carInfo['car_color'] = C('CAR_COLOR.' . $carInfo['car_color']); //车颜色
        $carInfo['comefrom'] = $show_from[$comefrom['comefrom']]; //渠道来源
        $carInfo['plate'] = C('PLATE_PREFIX.' . $carInfo['plate_prefix']) . $carInfo['plate_suffix'];//车牌号
        $carInfo['vin'] = $carInfo['vin']; // VIN号
        $carInfo['transfer_limit'] = C('TRANSFER_LIMIT.' . $carInfo['transfer_limit']);//过户限制
        return $carInfo;
    }

    /**
     * 获取渠道来源信息
     *
     * @return mixed
     */
    private function get_from()
    {
        $from = M("come_from a")->join('(SELECT from_id,from_name,sort FROM au_come_from WHERE pid=-2 AND is_delete=0) AS b ON a.pid=b.from_id')
            ->field("a.from_id,a.from_name,b.from_name AS pname,b.from_id AS pid,b.sort AS psort")
            ->where("a.pid!=-2 AND a.is_delete=0")
            ->order("psort ASC,pid DESC")
            ->select();
        foreach ($from as $key => $val) {
            $show_from[$val['from_id']] = $val['pname'] . '-' . $val['from_name'];
        }
        return $show_from;
    }

    /**
     * 争议
     */
    public function dispute()
    {
        $arr = $this->getDetailData();
        $data = [
            'purchase_order' => $arr['purchase_order'],
            'car_info' => $arr['car_info'],
        ];

        $this->assign('data', $data);
        $this->display();
    }

    /**
     *  提交争议数据
     */
    public function saveDispute()
    {
        $remark = I('request.remark');
        $purchaseOrderId = I('request.id');

        if (empty($remark)) {
            $this->helpJsonResult(422, "备注不能为空!");
            return;
        }
        $arr = $this->getDetailData();
        $status = $arr['purchase_order']['status'];
        if ($status != 1) {
            $this->helpJsonResult(422, "此时不能发起争议!");
        }

        $sid = $arr['purchase_order']['sid'];
        $orderInfo = AuOrder::getNewestOrderBySid($sid);

        if ($orderInfo['status'] != '9' && $orderInfo['status'] != '10') {  //只有待过户和过户中的拍单，才能发起争议
            $this->helpJsonResult(422, "此时的拍单不能发起争议!");
        }
        $condition['order_id'] = $orderInfo['order_id']; //拍单号
        $condition['od_type'] = 2; //客户类型 2 车主
        $condition['order_status'] = $orderInfo['status'];//拍单状态
        $disputeCount = Dispute::getDisputeByPurchaseOrder($condition);
        if ($disputeCount > 0) { //查看该采购单是否发起过争议
            $this->helpJsonResult(422, "车主不能发起二次争议!");
        }

        $carId = $orderInfo['car_id']; //车辆编号
        $carObj = new Car($carId);

        $carInfo = $carObj->detail();
        $carInfo = $this->sortingCarData($carInfo);

        $data['order_status'] = $orderInfo['status'];
        $data['po_id'] = $purchaseOrderId; //采购Id
        $data['po_no'] = $arr['purchase_order']['purchase_order_nu']; //采购单编号
        $data['order_id'] = $orderInfo['order_id'];
        $data['order_no'] = $orderInfo['order_no'];
        $data['car_id'] = $carInfo['car_id'];
        $data['car_no'] = $carInfo['car_no'];
        $data['car_plate_number'] = $carInfo['plate'];//车牌号',
        $data['od_id'] = $carInfo['owner_id']; //车商ID/车主ID',
        $data['od_type'] = '2';//'客户类型(1:车商 2:车主)',
        $data['remark'] = $remark;   // '争议备注',
        $data['dispute_reason'] = '2'; //争议原因(1:车况不符 2:过户超时)',
        $data['emp_id'] = $this->emp_id;  // 员工编号',
        $data['status'] = '1'; //状态(1:待审核 2:已通过 3:驳回 )',
        $data['auditing_result'] = ''; // 审核结果(1:通过 2:驳回 3:违约)',
        //`reject_result  //驳回原因',
        $data['createtime'] = date('Y-m-d H:i:s', time()); // '创建时间',

        $result = Dispute::DisputeAdd($data);
        if ($result) {
            $this->helpJsonResult(200, "提交成功!");
        } else {
            $this->helpJsonResult(400, "提交失败!");
        }
    }


    /**
     * 保存违约数据
     */
    public function saveDefault()
    {
        $arr = $this->getDetailData();
        $status = $arr['purchase_order']['status'];
        if ($status != 1) {
            $this->helpJsonResult(422, "此时不能发起违约!");
        }

        $sid = $arr['purchase_order']['sid'];
        $orderData = AuOrder::getNewestOrderBySid($sid);

        //$orderData = $orderObj->detail();
        if ($orderData['status'] < 5 || $orderData['status'] > 10) { //只有在车主确认和过户完成之前，才能发起违约
            $this->helpJsonResult(422, "此时的拍单不能发起违约!");
        }

        $carId = $orderData['car_id']; //车辆编号
        $carObj = new Car($carId);
        $carInfo = $carObj->detail();
        $carInfo = $this->sortingCarData($carInfo);

        $data['order_status'] = $arr['order_info']['status'];
        $data['po_id'] = $arr['purchase_order']['id']; //采购单Id
        $data['po_no'] = $arr['purchase_order']['purchase_order_nu']; //采购单编号
        $data['order_id'] = $orderData['order_id'];
        $data['order_no'] = $orderData['order_no'];
        $data['car_id'] = $carInfo['car_id'];
        $data['car_no'] = $carInfo['car_no'];
        $data['sid'] = $carInfo['sid'];
        $data['car_plate_number'] = $carInfo['plate'];
        $data['source'] = '9'; //来源(1:4S回车违约 2:复检违约 3:签约违约 4:验车违约 5:车商付款跟踪违约 6:过户 7:车商争议 8:车主争议 9:车主违约 )',
        $data['modify_reason'] = '4'; //卖方违约
        $data['originator_type'] = '2'; //'发起人类型:1车商2车主3仲裁人员',
        $data['originator'] = $this->emp_id; //发起人编号
        $data['originator_name'] = $this->user_info['real_name']; // 发起人姓名

        $result = ChangeOrder::CreateChangeOrder($data);
        if ($result) {
            $this->helpJsonResult(200, "提交成功!");
        } else {
            $this->helpJsonResult(400, "提交失败!");
        }
    }

    /**
     * 锁定采购单
     */
    public function lockPurchaseOrder()
    {
        $id = I('request.id');
        $purchaseOrderObj = new PurchaseOrder($id);
        $result = $purchaseOrderObj->lockById();
        if ($result) {
            $this->helpJsonResult(200, "提交成功!");
        } else {
            $this->helpJsonResult(422, "提交失败!");
        }
    }

    /**
     * 解锁采购单
     */
    public function unlockPurchaseOrder()
    {
        $id = I('request.id');
        $purchaseOrderObj = new PurchaseOrder($id);
        $result = $purchaseOrderObj->unLockById();
        if ($result) {
            $this->helpJsonResult(200, "提交成功!");
        } else {
            $this->helpJsonResult(422, "提交失败!");
        }
    }


}